from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
from storages.backends.s3boto3 import S3Boto3Storage
import os


class HeadImageStorage(S3Boto3Storage):
    """用户头像专用的云存储"""
    pass


def user_avatar_path(instance, filename):
    """
    自定义头像上传路径
    使用用户ID命名，保留原文件扩展名
    例如: avatars/user_123.jpg
    """
    # 获取文件扩展名
    ext = os.path.splitext(filename)[1]
    # 使用用户ID命名文件
    new_filename = f'user_{instance.id}{ext}'
    return os.path.join('avatars', new_filename)


class UserManager(BaseUserManager):
    """自定义用户管理器"""

    def create_user(self, email, name, password=None, **extra_fields):
        """创建普通用户"""
        if not email:
            raise ValueError('用户必须有邮箱地址')

        email = self.normalize_email(email)
        user = self.model(email=email, name=name, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, name, password=None, **extra_fields):
        """创建超级用户"""
        extra_fields.setdefault('role', 'admin')
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        return self.create_user(email, name, password, **extra_fields)


class User(AbstractBaseUser, PermissionsMixin):
    """自定义用户模型"""

    ROLE_CHOICES = [
        ('user', '普通用户'),
        ('creator', '创作者'),
        ('admin', '管理员'),
    ]

    email = models.EmailField(unique=True, verbose_name='邮箱')
    name = models.CharField(max_length=50, verbose_name='用户名')
    avatar = models.ImageField(
        upload_to=user_avatar_path,
        storage=HeadImageStorage(),
        default='avatars/default.png',
        verbose_name='头像',
        blank=True,
        null=True
    )
    bio = models.TextField(
        default='这个人很懒，什么都没有留下...',
        verbose_name='个人简介'
    )
    role = models.CharField(
        max_length=10,
        choices=ROLE_CHOICES,
        default='user',
        verbose_name='角色'
    )

    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    is_staff = models.BooleanField(default=False, verbose_name='是否员工')

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

    class Meta:
        db_table = 'users'
        verbose_name = '用户'
        verbose_name_plural = '用户'
        ordering = ['-created_at']

    def __str__(self):
        return self.email

    @property
    def stories_count(self):
        """用户故事数量"""
        return self.stories.count()

    @property
    def likes_received(self):
        """用户收到的总点赞数"""
        from stories.models import Story
        return sum(story.likes for story in self.stories.all())
